package com.yonyou.crm.sys.role.ctrl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sys.dataright.entity.RightTypeVO;
import com.yonyou.crm.sys.dataright.rmitf.IRightRmService;
import com.yonyou.crm.sys.role.entity.FuncresourceVO;
import com.yonyou.crm.sys.role.entity.FunctionVO;
import com.yonyou.crm.sys.role.entity.RoleFuncPerVO;
import com.yonyou.crm.sys.role.entity.RoleVO;
import com.yonyou.crm.sys.role.rmitf.IFuctionRmService;
import com.yonyou.crm.sys.role.rmitf.IRoleRmService;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.iuap.context.InvocationInfoProxy;

@RestController
@RequestMapping(value = "/sys/roles")
public class RoleCtrl {

	@Autowired
	private IRoleRmService service;
	@Autowired
	private IRightRmService rightRmService;
	
	@Autowired	
	private IFuctionRmService fuctionRmService;
	
	@RequestMapping(value = "/roletypes", method = RequestMethod.GET)
	public Object getRoleTypes(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		List<Map<String, Object>> roleTypeList = service.getRoleTypes();
		JSONObject result = new JSONObject();
		result.put("data", roleTypeList);
		return ResponseUtil.getObject(result);
	}

	/**
	 * 角色分配用户
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "{roleId}/users/assign", method = RequestMethod.POST)
	public Object assignUser(@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String userIdsStr = paramObj.getString("userIds");
		if (StringUtils.isEmpty(userIdsStr)||"".equals(userIdsStr)) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "角色和用户id不能为空");
		}
		String[] userIds = userIdsStr.split(",");
		boolean flag = service.assignUser(roleId, userIds);
		if(flag){
			Page<UserVO> users = service.getPersonals(getRequestPage(paramObj),roleId);
			return ResponseUtil.getObject(users);
		}else{
			throw new CrmMessageException("分配失败");
		}
		
	}
	
	/**
	 * 删除用户
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "unassign", method = RequestMethod.DELETE)
	public Object unAssignUser(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);

		long roleId = paramObj.getLong("roleId");
		String userIdsStr = paramObj.getString("userIds");
		String[] userIds = userIdsStr.split(",");

		boolean flag = service.unAssignUser(roleId, userIds);
		if(flag){
			Page<UserVO> personals = service.getPersonals(getRequestPage(paramObj),roleId);
			return ResponseUtil.getObject(personals);
		}else{
			throw new CrmMessageException("移除失败");
		}
	}
	
	

	/**
	 * 角色左侧列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		Map<String, Object> param = (Map<String, Object>) paramObj.get("searchMap");
		param.put("tenantId",  InvocationInfoProxy.getTenantid());
		List<RoleVO> roleList = service.getRoleListByTenantId(param);
		JSONObject result = new JSONObject();
		result.put("data", roleList);
		
		return ResponseUtil.getObject(result);
	}

	/**
	 * 查询用户所属角色
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
	public Object getUserRole(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse
			response) throws CrmMessageException {

		if (id == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
		}
		List<RoleVO> roleList= service.getUserRole(id);
		JSONObject result = new JSONObject();
		result.put("data", roleList);
		return ResponseUtil.getObject(result);
	}


	/**
	 * 角色详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
		}		
		
		return ResponseUtil.getObject(service.getRoleDetail(id));
	}
	
	
	/**
	 * 新增角色
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

 		RoleVO role = RequestUtil.getVO(request, RoleVO.class);
 		if(role.getName()==null || "".equals(role.getName())){
 			throw new CrmMessageException("角色名称不能为空");
 		}
		role = service.insertRole(role);
		
		if (role.getId() == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "获取自增主键为空");
		}
				
		return ResponseUtil.getObject(role);
	}

	/**
	 * 修改角色
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		RoleVO role = RequestUtil.getVO(request, RoleVO.class);		
		if (role == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "转换实体失败");
		}
		
		role.setId(id);
		

		RoleVO newRole = service.updateRole(role);
		
		return ResponseUtil.getObject(newRole);
	}
	
		
	/**
	 * 删除角色
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") Long id ,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "id不能为空");
		}
		
		int successNum = service.deleteRole(id);
		JSONObject json = new JSONObject();
		json.put("flag", successNum);
		return ResponseUtil.getObject(json);
	}
	
	/**
	 * 获取角色-人员列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value="/{roleId}/users",method = RequestMethod.GET)
	public Object getPersonals (@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException{
		JSONObject paramObj = RequestUtil.getParamObject(request);
		Page<UserVO> personals = service.getPersonals(getRequestPage(paramObj),roleId);
		return ResponseUtil.getObject(personals);
	}
	
	/**
	 * 获取角色-人员新增列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value="/{roleId}/add/users",method = RequestMethod.GET)
	public Object getPersonalsAddList (@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException{
		JSONObject paramObj = RequestUtil.getParamObject(request);
		 String orgId = InvocationInfoProxy.getParameter(LoginContextConstant.OrgId);

		String name = "".equals(paramObj.getString("name"))?null:paramObj.getString("name");
		List<UserVO> personals = service.getAddPersonals(name,orgId,roleId);
		JSONObject result = new JSONObject();
		result.put("data", personals);
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 获取角色参照列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value="/ref",method = RequestMethod.GET)
	public Object getRefList(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException{
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String searchMap = null;
		if(paramObj!=null){
			searchMap = paramObj.get("searchMap").toString();
		}
		List<RoleVO> roleList = service.getRefList(searchMap);
		JSONObject result = new JSONObject();
		result.put("data", roleList);
		
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 获取功能节点及功能权限
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "/{roleId}/funcs",method = RequestMethod.GET)
	public Object getFunctionList(@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException{
		
		if(roleId==null){
			throw new CrmMessageException(PCCodeConstant.ServerError, "角色id不能为空");
		}
		List<FunctionVO> functionVOs = fuctionRmService.getFunctiuonList(roleId);
		JSONObject result = new JSONObject();
		result.put("data", functionVOs);
		return ResponseUtil.getObject(result);
		
	}
		
	/**
	 * 角色分配功能权限
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/{roleId}/func/assign",method = RequestMethod.POST)
	public void dealRoleFuncPer(@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response){
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String checked = paramObj.getString("checked");
		
		assignFuncPer(paramObj,roleId,checked);
	}
		
	private void assignFuncPer(JSONObject paramObj, Long roleId, String checked) {
		List<RoleFuncPerVO> roleFuncPerVOs = new ArrayList<>();
		String funcperIdsStr = paramObj.getString("funcperIds");
		String[] funcperIds  = funcperIdsStr.split(",");
		String tenantId = InvocationInfoProxy.getTenantid();
		for(String funcperId:funcperIds){
			RoleFuncPerVO roleFuncPerVO = new RoleFuncPerVO();
			roleFuncPerVO.setFuncperId(Long.valueOf(funcperId));
			roleFuncPerVO.setRoleId(paramObj.getLong("roleId"));
			roleFuncPerVO.setTenantId(Long.valueOf(tenantId));
			roleFuncPerVOs.add(roleFuncPerVO);
		}
		fuctionRmService.assignFuncPer(roleFuncPerVOs,checked);
	}


	/**
	 * 获取功能资源
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/{roleId}/funcres",method = RequestMethod.GET)
	public Object getUnhaveFuncResourceList(@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response){
		
		List<FuncresourceVO> funcResourceList = fuctionRmService.getUnhaveFuncResourceList(roleId);
		JSONObject result = new JSONObject();
		result.put("data", funcResourceList);
		return ResponseUtil.getObject(result);
		
	}
	
	
	/**
	 * 分配数据权限
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/{roleId}/right/assign",method = RequestMethod.POST)
	public void rightAssign(@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response){
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String typeId = paramObj.getString("typeId");
		rightRmService.assign(roleId,typeId);
	}
	
	/**
	 * 获取数据权限
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/{roleId}/right",method = RequestMethod.GET)
	public Object right(@PathVariable("roleId")Long roleId,HttpServletRequest request, HttpServletResponse response){
		
		List<RightTypeVO> para = rightRmService.right(roleId);
		
		JSONObject result = new JSONObject();
		result.put("data", para);
		return ResponseUtil.getObject(result);
	}
	
	private Page<UserVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {
		
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		
		return new Page<UserVO>(page, pageSize);
	}
	
	private String getRoleTypeByUserId() {
		String userId = InvocationInfoProxy.getParameter(LoginContextConstant.UserId);//当前登陆人id
		List<RoleVO> userRole = service.getUserRole(Long.valueOf(userId));
		return userRole.get(0).getType().toString();
	}
	
}
